const Service = require('egg').Service;
const prefix = 'https://api.weixin.qq.com/sns';
const api = {
  authorize:'https://open.weixin.qq.com/connect/oauth2/authorize',
  access_token:`${prefix}/oauth2/access_token`,
  userinfo:`${prefix}/userinfo`
}
class wechatOauth extends Service {
  // 用户授权url
  getAuthorizeUrl(scope='snsapi_base',target,state) {
    const { wechat } = this.config;
    const url = `${api.authorize}?appid=${wechat.appID}&redirect_uri=${encodeURIComponent(target)}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`;
    return url;
  }
  // 根据code获取用户信息
  async getUserInfoByCode(code){
    const { access_token, openid } = await this.fetchAccessToken(code);
    const userinfo = await this.getUserInfo(access_token, openid);
    return userinfo;
  }
  // 拉取验证权限用的access_token
  async fetchAccessToken(code) {
    const { wechat } = this.config;
    const url = `${api.access_token}?appid=${wechat.appID}&secret=${wechat.appSecret}&code=${code}&grant_type=authorization_code`;
    const { data } = await this.ctx.curl(url, {
      dataType: 'json'
    });
    return data;
  }
  async getUserInfo(accessToken, openid, lang='zh_CN') {
    const url = `${api.userinfo}?access_token=${accessToken}&openid=${openid}&lang=${lang}`;
    const data = await this.ctx.curl(url, {
      dataType: 'json'
    });
    return data;
  }
}

module.exports = wechatOauth;